#include <windows.h>

#include "support.h"
#include "window.h"
#include "monitors.h"
#include "taskbar.h"

HMODULE mod;

typedef void (*install_hooks_proc)(HWND);
typedef void (*free_hooks_proc)(void);
typedef void (*init_debug_proc)(void);
typedef void (*bypass_hooks_proc)(int);
typedef void (*cleanup_proc)(void);

bypass_hooks_proc bypass_hooks_fn;
cleanup_proc cleanup_fn;

static LONG WINAPI crash_handler_callback(LPEXCEPTION_POINTERS);

void install_hooks(void)
{
	mod = LoadLibrary("MonMan.dll");
	if(!mod) fatal("MonMan.dll not found");
	
	((install_hooks_proc)GetProcAddress(mod, "install_hooks"))(main_window);
	
	bypass_hooks_fn = (bypass_hooks_proc)GetProcAddress(mod, "bypass_hooks");
	
	//if(!RegisterShellHookWindow(main_window))
	//	fatal("Shell error");
}
		
void free_hooks(void)
{
	//DeregisterShellHookWindow(main_window);
	
	((free_hooks_proc)GetProcAddress(mod, "free_hooks"))();
	FreeLibrary(mod);
}

void bypass_hooks(int on)
{
	bypass_hooks_fn(on);
}

void install_crash_handler(cleanup_proc fn)
{
	cleanup_fn = fn;
	SetUnhandledExceptionFilter(&crash_handler_callback);
}

static LONG WINAPI crash_handler_callback(LPEXCEPTION_POINTERS info)
{
	SetUnhandledExceptionFilter(0);
	MessageBox(0, "MonMan crashed", "", 0);
	cleanup_fn();
	return EXCEPTION_EXECUTE_HANDLER;
}

